/*
 * @Author: szx
 * @Date: 2022-04-09 13:18:11
 * @LastEditTime: 2022-04-09 13:47:30
 * @Description:
 * @FilePath: \leetcode\剑指offerII\043\043.js
 */
function TreeNode(val, left, right) {
    this.val = val === undefined ? 0 : val;
    this.left = left === undefined ? null : left;
    this.right = right === undefined ? null : right;
}

/**
 * @param {TreeNode} root
 */
var CBTInserter = function (root) {
    const parent = [root];
    let child = [];
    while (parent.length) {
        const len = parent.length;
        for (let i = 0; i < len; i++) {
            const node = parent[i];
            node.left && child.push(node.left);
            node.right && child.push(node.right);
        }
        const childLen = child.length;
        if (childLen > 0 && childLen == len * 2) {
            parent = child;
            child = [];
        } else {
            for (let i = Math.floor((childLen + 1) / 2); i > 0; i--) {
                parent.shift();
            }
            break;
        }
    }
    this.parent = parent;
    this.child = child;
    this.root = root;
};

/**
 * @param {number} v
 * @return {number}
 */
CBTInserter.prototype.insert = function (v) {
    const parent = this.parent;
    const child = this.child;

    const newChild = new TreeNode(v);
    child.push(newChild);
    if (!parent.left) {
        parent[0].left = newChild;
    } else if (!parent.right) {
        parent[0].right = newChild;
    } else {
        parent.shift();
        if (parent.length == 0) {
            parent = child;
            child = [];
        }
        parent[0].left = newChild;
    }
    return parent[0]
};

/**
 * @return {TreeNode}
 */
CBTInserter.prototype.get_root = function () {
    return this.root;
};

/**
 * Your CBTInserter object will be instantiated and called as such:
 * var obj = new CBTInserter(root)
 * var param_1 = obj.insert(v)
 * var param_2 = obj.get_root()
 */
